package com.swak.boot.config.job;

import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

import com.swak.boot.config.job.JobStorageAutoConfiguration.JobStorageCondition;
import com.swak.boot.config.job.storage.H2StorageAutoConfiguration;
import com.swak.boot.config.job.storage.MysqlStorageAutoConfiguration;

/**
 * 配置 StorageService.
 * 
 * @author 618lf
 */
@Configuration
@Conditional(JobStorageCondition.class)
@EnableConfigurationProperties(JobProperties.class)
@Import({ MysqlStorageAutoConfiguration.class, H2StorageAutoConfiguration.class })
public class JobStorageAutoConfiguration {

	static class JobStorageCondition extends SpringBootCondition {

		private static final String DATASOURCE_URL_PROPERTY = "spring.job.db.url";

		@Override
		public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
			ConditionMessage.Builder message = ConditionMessage.forCondition("StorageService");
			if (hasDataSourceUrlProperty(context)) {
				return ConditionOutcome.match();
			}
			return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is not set"));
		}

		private boolean hasDataSourceUrlProperty(ConditionContext context) {
			Environment environment = context.getEnvironment();
			if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) {
				try {
					return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY));
				} catch (IllegalArgumentException ex) {
					// Ignore unresolvable placeholder errors
				}
			}
			return false;
		}
	}
}
